package cz.none.bezbarier.web.util;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

public class LoggingExceptionResolver extends SimpleMappingExceptionResolver {
	private Collection<String> ignoredExceptions;

	private static final Logger LOG = LoggerFactory.getLogger(SimpleMappingExceptionResolver.class);

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) {
		for (String ignored : ignoredExceptions) {
			try {
				Class<?> exClass = Class.forName(ignored.trim());
				if (exClass.isInstance(ex)) {
					return null;
				}
			} catch (Exception e) {
				LOG.warn(
						"The class [{}] is not a valid class. This probably indicates a configuration problem.",
						ignored);
			}
		}
		return super.doResolveException(request, response, handler, ex);
	}

	@Override
	protected void logException(Exception ex, HttpServletRequest request) {
		if (ex instanceof ConstraintViolationException) {
			LOG.warn("Some exception occured during processing: {}, {}", new Object[] { ex,
					((ConstraintViolationException) ex).getConstraintViolations() });
		} else {
			LOG.warn("Some exception occured during processing: {}", new Object[] { ex });
		}

		LOG.warn("Stack trace:", ex);

	}

	public void setIgnoredExceptions(Collection<String> ignoredException) {
		this.ignoredExceptions = ignoredException;
	}

}
